package com.qclix.inv.webui;

import com.qclix.inv.*;
import com.qclix.inv.webui.jsonobj.JSonContract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping(value="/contract")
public class ContractController {
    private static Logger logger = LoggerFactory.getLogger(ContractController.class);

    @Autowired
    private InvoiceService invoiceService;

    public InvoiceService getInvoiceService() {
        return invoiceService;
    }

    public void setInvoiceService(InvoiceService invoiceService) {
        this.invoiceService = invoiceService;
    }

    @RequestMapping(value = "/autocomplete", method = RequestMethod.GET)
    public
    @ResponseBody
    JSonContract[] getContractWithMatchingReference(HttpServletRequest request, HttpServletResponse response) {
        List<Contract> contracts = null;
        try {
            contracts = invoiceService.getAllContracts();
        } catch (Throwable e) {
            logger.error("Could not retrieve the contracts.", e);
            return null;
        }

        List<Contract> matchingContractList = new ArrayList<Contract>();
        String pattern = request.getParameter("term");
        if (pattern != null) {
            pattern = pattern.toUpperCase();
            for (Contract contract : contracts) {
                if (contract.getReference().toUpperCase().contains(pattern)) {
                    matchingContractList.add(contract);
                }
            }
        }

        JSonContract[] matchingContracts = new JSonContract[matchingContractList.size()];
        for (int i = 0; i < matchingContractList.size(); i++) {
            matchingContracts[i] = JSonObjTranslator.getJSon(matchingContractList.get(i));
        }
        return matchingContracts;
    }

    @RequestMapping(value="new", method=RequestMethod.POST)
    @ResponseBody
    Map<String, ? extends Object> newContract(@RequestBody JSonContract contract) {
        Contract domainContract = JSonObjTranslator.getModel(contract);
        logger.debug("Creating " + domainContract);
        try {
            invoiceService.saveContract(domainContract);
        } catch (Throwable e) {
            logger.error("Error saving " + domainContract, e);
        }
        logger.info(domainContract.toString() + " created");
        Map<String, JSonContract> returnMap = new HashMap<String, JSonContract>();
        returnMap.put(domainContract.getReference(), contract);
        return returnMap;
    }

    @RequestMapping(value="new-contract")
    public ModelAndView newInvoicePage() {
        return new ModelAndView("new-contract");
    }
}
